package com.douxg.learning.tool.jsch;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Auther douxg
 * @Date 2020/10/27 19:50
 */
public class JschTest {
    public static void main(String[] args) {
        Map<String, String> sftpDetails = new HashMap<>();
        sftpDetails.put("host", "192.168.12.51");
        sftpDetails.put("port", "22");
        sftpDetails.put("username", "asap");
        sftpDetails.put("password", "1qazXSW@3edc");
        for (int i = 0; i < 100; i++) {
            try {
                getSftpChannel(sftpDetails, 6000, null, null);
                System.out.println(i + 1);
            } catch (JSchException e) {
                e.printStackTrace();
            }
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {

            }
        }
    }

    public static Map getSftpChannel(Map<String, String> sftpDetails, int timeout, Channel channel, Session session) throws JSchException {
        String ftpHost = (String) sftpDetails.get("host");
        String port = (String) sftpDetails.get("port");
        String ftpUserName = (String) sftpDetails.get("username");
        String ftpPassword = (String) sftpDetails.get("password");
        int ftpPort = 22;
        if (port != null && !port.equals("")) {
            ftpPort = Integer.valueOf(port);
        }

        JSch jsch = new JSch();
        session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
        if (ftpPassword != null) {
            session.setPassword(ftpPassword);
        }

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setTimeout(timeout);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        Map map = new HashMap();
        map.put("session", session);
        map.put("channel", channel);
        channel.disconnect();
        session.disconnect();
        return map;
    }
}
